/*
* Copyright (c) 2016 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
*/
package com.hyyt.shopjsp.util.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.hyyt.shopjsp.util.common.Utils;

/**
 * CustomHttpRequest HTTP请求接口类
 */

public class CustomHttpRequest {
	
	/**
     * 向指定URL发送Post方法的请求
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 json 的形式。
     * @return stringJson 所代表远程资源的响应结果
     */
     public static String sendHttpClientPost(String url, String json) {
    	int socketTimeout = 10000;
    	int connectTimeout = 10000;
    	int connectionRequestTimeout = 10000;
    	int successCode = 200;
    	//设置请求和传输超时时间
		RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();
		//创建链接请求执行对象
    	CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
    	//接收返回值
    	CloseableHttpResponse response = null;
    	//执行post方法
		HttpPost httpPost = new HttpPost(url);
		try{
			//编译json参数数据
			json = new String(json.getBytes("utf-8"), "iso8859-1");
			//转化为可用的参数对象
			StringEntity stringEntity = new StringEntity(json);
			stringEntity.setContentEncoding("iso8859-1");
			stringEntity.setContentType("application/json; encoding=iso8859-1");
			//设置传递参数
			httpPost.setEntity(stringEntity);
			//执行传参，并且得到返回结果
			response = httpclient.execute(httpPost);
			//返回结果正确
			if (response.getStatusLine().getStatusCode() == successCode){
				HttpEntity entity = response.getEntity();
				String stringJson = EntityUtils.toString(entity, "utf-8");
				return stringJson;
			}else{
				String errorCode = String.valueOf(response.getStatusLine().getStatusCode());
				return errorCode;
			}
		} catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (UnsupportedEncodingException e1) {  
            e1.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            // 关闭连接,释放资源
            try {
            	response.close();
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }
        }
		return "";
    }
	
    /**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
			// 连接超时
            connection.setConnectTimeout(25000);
			// 读取超时 --服务器响应比较慢，增大时间
            connection.setReadTimeout(25000);
			HttpURLConnection.setFollowRedirects(true);
			// 请求方式
			connection.setRequestMethod("GET");
            // 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0");
            // 建立实际的连接
            connection.connect();
            /*
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            */
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            if (connection != null) {
            	connection.disconnect();
			}
        } catch (Exception e) {
//            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
			// 连接超时setConnectTimeout：设置连接主机超时（单位：毫秒）
			conn.setConnectTimeout(25000);
			// 读取超时 --服务器响应比较慢，增大时间setReadTimeout：设置从主机读取数据超时（单位：毫秒）
			conn.setReadTimeout(25000);
            // 设置通用的请求属性
			// 设定传送的内容类型是可序列化的java对象 
			// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException) 
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Content-type", "application/x-java-serialized-object");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0");
            // Post 请求不能使用缓存 
            conn.setUseCaches(false);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 连接，从上述第2条中url.openConnection()至此的配置必须要在connect之前完成
            conn.connect(); 
            // 获取URLConnection对象对应的输出流
            // 此处getOutputStream会隐含的进行connect(即：如同调用上面的connect()方法， 所以在开发中不调用上述的connect()也可以)。
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
    		StringBuffer bufferRes = new StringBuffer();
    		// 调用HttpURLConnection连接对象的getInputStream()函数, 
    		// 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));// <===注意，实际发送请求的代码段就在这里
			String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
			result = bufferRes.toString();
        } catch (Exception e) {
//            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        } finally{//使用finally块来关闭输出流、输入流
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
    
	/**
	 * 将json字符串转换成map对象
	 * @return Map
	 */
	public static Map<String, String> parseJsonStringToMap(String jsonString) {
		JSONArray arry = JSONArray.fromObject("[" + jsonString + "]");
		Map<String, String> jsonMap = new HashMap<String, String>();
		if(arry!=null){
			for (int i = 0; i < arry.size(); i++) {
				JSONObject jsonObject = arry.getJSONObject(i);
				for (Iterator<?> iter = jsonObject.keys(); iter.hasNext();) {
					String key = (String) iter.next();
					String value = jsonObject.get(key).toString();
					jsonMap.put(key, value);
				}
			}
		}
		return jsonMap;
	}
	/**
	 * 通过InputStream流的方式来获取数据
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	public static String receivePost(HttpServletRequest request) {
		// 读取请求内容
		BufferedReader br = null;
		String reqBody = "";
		try {
			br = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
			String line = null;
			StringBuilder sb = new StringBuilder();
			while((line = br.readLine())!=null){
				sb.append(line);
			}
			// 将资料解码
			reqBody = URLDecoder.decode(sb.toString(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{//使用finally块来关闭输出流、输入流
			try {
				if(Utils.objectIsNotEmpty(br)){
					br.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
		return reqBody;
    }
	public static String getBufferedReader(BufferedReader br){
		String reqBody = "";
		try {
			String line = null;
			StringBuilder sb = new StringBuilder();
			while((line = br.readLine())!=null){
				sb.append(line);
			}
			// 将资料解码
			reqBody = URLDecoder.decode(sb.toString(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{//使用finally块来关闭输出流、输入流
			try {
				if(Utils.objectIsNotEmpty(br)){
					br.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
		return reqBody;
	}

}